package retrofit.boot.annotation;

import lombok.Data;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.PriorityOrdered;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import retrofit.Endpoint;
import retrofit.boot.autoconfigure.RetrofitClientProperties;
import retrofit.boot.autoconfigure.RetrofitContext;
import retrofit.boot.constants.RetrofitOrder;
import retrofit.boot.util.RetrofitUtils;

/**
 * Created by wulg on 2019/11/6
 * description:
 */
@Data
public final class RetrofitEndpointFactoryBean implements FactoryBean<Object>, InitializingBean, PriorityOrdered {

    private String name;

    private String url;

    @Autowired(required = false)
    private EndpointLoadBalancer loadBalancer;

    @Autowired
    private RetrofitContext retrofitContext;


    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(this.name, "Name must be set");
    }

    @Override
    public Object getObject() throws Exception {
        RetrofitClientProperties.RetrofitClientConfiguration retrofitClientConfig = retrofitContext.getClientConfig(name);
        if(loadBalancer != null && loadBalancer.supports(name)){
            //默认方式 支持url动态
        } else if(StringUtils.hasText(retrofitClientConfig.getUrl())){
            loadBalancer = name -> retrofitClientConfig.getUrl();
        } else if(StringUtils.hasText(url)){
            loadBalancer = name -> url;
        }
        Assert.hasText(RetrofitUtils.rebuildUrl(loadBalancer.chooseUrl(name)), "Endpoint must be configured! name="+name);
        return new Endpoint() {
            @Override
            public String getUrl() {
                return loadBalancer.chooseUrl(name);
            }
            @Override
            public String getName() {
                return name;
            }
        };
    }

    @Override
    public Class<?> getObjectType() {
        return Endpoint.class;
    }

    @Override
    public int getOrder() {
        return RetrofitOrder.getEndpointOrder();
    }
}
